package com.demo.servicelmpl;

import com.demo.bean.User;
import com.demo.mapper.UserMapper;
import com.demo.service.UserService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.LinkedHashMap;

/**
 * @author 李天航
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public Object addUser(User user) {
        LinkedHashMap<String, Object> resultMap=new LinkedHashMap<>();
        try {
            userMapper.addUser(user);
            resultMap.put("status",200);
            resultMap.put("msg","添加成功");
        }
        catch (DuplicateKeyException e)
        {
            resultMap.put("status",500);
            resultMap.put("msg","用户名已经存在");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            resultMap.put("status",500);
            resultMap.put("msg",e.getMessage());
        }
        return resultMap;
    }

    @Override
    public Object deleteUserById(String userAccount) {
        LinkedHashMap<String, Object> resultMap=new LinkedHashMap<>();
        try {
            userMapper.deleteUser(userAccount);
            resultMap.put("status",200);
            resultMap.put("msg","删除成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            resultMap.put("status",500);
            resultMap.put("msg",e.getMessage());
        }
        return resultMap;
    }

    @Override
    public Object updateUser(User user) {
        LinkedHashMap<String, Object> resultMap=new LinkedHashMap<>();
        try {
            userMapper.updateUser(user);
            resultMap.put("status",200);
            resultMap.put("msg","修改成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            resultMap.put("status",500);
            resultMap.put("msg",e.getMessage());
        }
        return resultMap;
    }

    @Override
    public LinkedHashMap<String, Object> updatePwd(String nowPwd, User user, String lastPwd) {
        LinkedHashMap<String, Object> resultMap=new LinkedHashMap<>();
        try {
            if(user.getUserPwd().equals(lastPwd)) {
                user.setUserPwd(nowPwd);
                userMapper.updatePwd(user);
                resultMap.put("status", 200);
                resultMap.put("msg", "修改成功");
            }
            else
            {
                resultMap.put("status",500);
                resultMap.put("msg","原密码错误");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            resultMap.put("status",500);
            resultMap.put("msg",e.getMessage());
        }
        return resultMap;
    }
}
